﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;

namespace LOGISTCBUS.WebUI.Controllers
{
    [HandleError(View = "Error")]
    public class CostTypeController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        public ActionResult Edit(int? id)
        {
            var userLogged = (User)this.Session["user"];
            if (userLogged == null)
                return RedirectToAction(@"LogOut", @"Account");

            if (id.HasValue)
            {
                var costType = new CostTypeDAO().selectById(Convert.ToInt32(id));
                this.ViewData[@"costType"] = costType == null ? new CostType() : costType;
            }

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(int id)
        {
            var ct = id > 0 ? new CostTypeDAO().selectById(id) : new CostType();
            var culture = new CultureInfo("pt-BR");
            var aux = true;

            if (!String.IsNullOrEmpty(Request.Params["name"]))
                ct.Name = Request.Params["name"];
            if (!String.IsNullOrEmpty(Request.Params["value"]))
                ct.Value = Convert.ToDecimal(Request.Params["value"], culture);
            if (!String.IsNullOrEmpty(Request.Params["description"]))
                ct.Description = Request.Params["description"];

            if (ct.Id > 0)
                aux = new CostTypeDAO().update(ct);
            else
                aux = new CostTypeDAO().insert(ct);

            var obj = new
            {
                success = aux,
                message = "Tipo de despesa salva com sucesso!"
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Search()
        {
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var name = String.IsNullOrEmpty(Request.Params[@"name"]) ? string.Empty : Request.Params[@"name"].ToString();
            var pageSize = MvcApplication.pageSize;
            var types = new CostTypeDAO().select(name, page, pageSize);
            var count = new CostTypeDAO().getCount(name);
            var totalPages = (count < pageSize) ? 1 : Math.Ceiling(Convert.ToDecimal(count) / pageSize);
            var lst = new List<object>();

            foreach (var ct in types)
            {
                lst.Add(new
                {
                    Id = ct.Id,
                    Name = ct.Name,
                    Value = String.Format("R$ {0:######0.00}", ct.Value)
                });
            }

            var obj = new
            {
                data = lst,
                currpage = page,
                totalpages = totalPages,
                totalrecords = count
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete()
        {
            var id = String.IsNullOrEmpty(Request.Params[@"id"]) ? 0 : Convert.ToInt32(Request.Params[@"id"]);
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var aux = true;

            if (id > 0)
            {
                var ct = new CostType() { Id = id };
                aux = new CostTypeDAO().delete(ct);
            }

            var obj = new
            {
                Message = "Registro removido com sucesso!",
                Success = aux,
                Page = page
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteAll()
        {
            var values = Request.Form["ids"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var aux = true;

            var lst = new List<CostType>();
            foreach (var val in values)
                if (!String.IsNullOrEmpty(val))
                    lst.Add(new CostType() { Id = Convert.ToInt32(val) });
            aux = new CostTypeDAO().delete(lst);

            var obj = new
            {
                Message = "Registro(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }
    }
}
